package io.renren.modules.demo.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.demo.dto.WenbenDTO;
import io.renren.modules.demo.entity.WenbenEntity;
import io.renren.modules.demo.excel.WenbenExcel;
import io.renren.modules.demo.service.WenbenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 
 *
 * @author Zyc 1227756953@qq.com
 * @since 1.0.0 2024-05-08
 */
@RestController
@RequestMapping("demo/wenben")
@Api(tags="")
public class WenbenController {
    @Autowired
    private WenbenService wenbenService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("demo:wenben:page")
    public Result<PageData<WenbenDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<WenbenDTO> page = wenbenService.page(params);
        return new Result<PageData<WenbenDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("demo:wenben:info")
    public Result<WenbenDTO> get(@PathVariable("id") Long id){
        WenbenDTO data = wenbenService.get(id);

        return new Result<WenbenDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("demo:wenben:save")
    public Result save(@RequestBody WenbenDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        wenbenService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("demo:wenben:update")
    public Result update(@RequestBody WenbenDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        wenbenService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("demo:wenben:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        wenbenService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("demo:wenben:export")
    @ApiImplicitParam(name = "id", value = "ID", paramType = "query", dataType = "String")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<WenbenDTO> list = wenbenService.list(params);

        for (WenbenDTO entry :list){
            System.out.println(entry);
        }
        ExcelUtils.exportExcelToTarget(response, null, "", list, WenbenExcel.class);
    }


    /**
     * execl导入接口
     * @param file
     * @throws Exception
     */
    @PostMapping("import")
    @ApiOperation("导入")
    @LogOperation("导入")
    @RequiresPermissions("demo:wenben:import")
    public Result  imp(@RequestBody MultipartFile file) throws Exception {
        System.out.println("导入方法使用");
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        inputStream.close();
        List<WenbenDTO> wenbenDTOS = reader.readAll(WenbenDTO.class);

        //ID读取不了，通过for循环读取
        int i=0;
        for (List<Object> line :reader.read()) {
            if (i==0){
                i++;
                continue;
            }
            WenbenDTO wenbenDTO = wenbenDTOS.get(i-1);
            Object id = line.get(0);
            double num=0;
            if (id instanceof String) {
                String str = (String) line.get(0);
                 num= Double.parseDouble(str);
            } else if (id instanceof Double) {
                num = (Double) line.get(0);
            } else {
                System.out.println("The value at index 0 is not a string or a double.");
                continue;
            }
            wenbenDTO.setId(num);
            wenbenDTOS.set(i-1,wenbenDTO);
            i++;
        }
        List<WenbenEntity> wenbenEntities = new ArrayList<WenbenEntity>();
        //对象属性拷贝
        for(WenbenDTO wenbenDTO : wenbenDTOS){
            WenbenEntity wenbenEntity = new WenbenEntity();
            BeanUtils.copyProperties(wenbenDTO,wenbenEntity);
            wenbenEntities.add(wenbenEntity);
        }
        Result<Object> result = new Result<>();
        try{
             wenbenService.insertBatch(wenbenEntities);

        }catch(Exception e){
            return result.error("导入失败");
        }
        System.out.println("成功了");
        result.success();
        return result;
    }

}